﻿using QGMiniGame;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using Newtonsoft.Json;

public class AdManager : MonoBehaviour
{
    public static bool IsOpenWorkTimeShield = false;//是否启用工作日屏蔽

    public static bool TestMode = false;//是否为测试包

    public static bool FirstLoad = true;//是否首次登录

    public static bool IsAutoPop = false;//是否开启自弹

    public static bool IsAddIcon = false;//是否创建过桌面图标

    public static bool IsNativeReplace = false; //是否开启原生替换

    public static string Company = "长沙优趣创想科技有限公司"; //隐私-公司
    public static string Email = "客服邮箱：3414758397@qq.com"; //隐私-联系方式

    public static string Owner = "著作权人：北京古鲁营销顾问有限公司"; //健康忠告-著作权人
    public static string License = "登记号：2025SR1507698"; //健康忠告v-登记号
    public static int AgeLimit = 12; //健康忠告-适龄 8 12 16

    //Banner，原生屏蔽时间
    public static int Year = 2025;
    public static int Month = 8;
    public static int Day = 20;
    public static int Hour = 19;

    private static string AppId = "105712532";
    private static string VideoId = "aef2cb28e7cb4da8aa19242eab007089";
    private static string CustomId = "63cda27125a2454ab2a5380fceb3f1a9";
    private static string BannerId = "91ab69f19cd0497fb8eb066af24b430e";

    // <summary>
    // 是否是屏蔽区域—默认被屏蔽，白包
    // </summary>
    public bool ShieldAddress = true;
    //获取的json数据
    private string GetjsonText;
    public bool isInit = false;
    //屏蔽区域
    string[] PinBiAddress = new string[] { "北京市", "上海市", "广州市", "深圳市", "东莞市" };

    static AdManager _instance;
    public static AdManager Instance
    {
        get
        {
            if (_instance == null)
            {
                GameObject gameObject = new GameObject("AdManager");
                _instance = gameObject.AddComponent<AdManager>();
                //_instance.AddBtn(null, null, null, null);
                DontDestroyOnLoad(gameObject);
            }
            return _instance;
        }
    }

    void NativeAutoPop()//自弹原生
    {
        ShowNative();
    }

    void CreatIconAutoPop()//添加桌面自弹
    {
        if (!IsAddIcon) AddDesktopIcon();
    }

    IEnumerator GetHoliday()
    {
        UnityWebRequest request = UnityWebRequest.Get("https://api.jiejiariapi.com/v1/holidays/" + DateTime.Now.Year);
        request.timeout = 2;//超时时间
        yield return request.SendWebRequest();
        try
        {
            //是否下载完成
            if (request.isDone)
            {
                bool isholiday = false;
                bool isoffday = false;
                if (request.isHttpError || request.isNetworkError)
                {
                    //    Debug.Log("下载失败"+request.error);
                }
                else
                {
                    GetjsonText = request.downloadHandler.text;
                    Debug.Log("下载成功！！" + GetjsonText);

                    //如果识别不到JsonConvert
                    //打开 Unity Editor → Window → Package Manager。
                    //点击 "+" → "Add package from git URL..."。
                    //输入：com.unity.nuget.newtonsoft-json                                    （官方版本）
                    //或者：https://github.com/jilleJr/Newtonsoft.Json-for-Unity.git#upm       （社区版本）
                    //点击 "Add"，等待安装完成返回脚本,如果还识别不到JsonConvert，则重启项目
                    Dictionary<string, Holiday> holidays = JsonConvert.DeserializeObject<Dictionary<string, Holiday>>(GetjsonText);

                    // 遍历数据
                    foreach (var pair in holidays)
                    {
                        //Debug.Log($"日期: {pair.Key}, 节日: {pair.Value.name}, 是否放假: {pair.Value.isOffDay}");
                        DateTime date = DateTime.Parse(pair.Key); // 自动解析标准格式
                        if (date.Year == DateTime.Now.Year && date.Month == DateTime.Now.Month && date.Day == DateTime.Now.Day)
                        {
                            isholiday = true;
                            if (pair.Value.isOffDay) isoffday = true;
                            break;
                        }
                    }


                }
                //工作日屏蔽
                if (isholiday)
                {
                    Debug.Log("节假日");
                    if (isoffday)
                    {
                        Debug.Log("放假");
                        ShieldAddress = false;
                    }
                    else
                    {
                        Debug.Log("调休补班");
                        if (DateTime.Now.Hour < 19 && DateTime.Now.Hour >= 7)
                        {
                            ShieldAddress = true;
                        }
                        else
                        {
                            ShieldAddress = false;
                        }
                    }
                }
                else
                {
                    Debug.Log("非节假日");
                    if (DateTime.Now.DayOfWeek == DayOfWeek.Saturday || DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
                    {
                        ShieldAddress = false;
                    }
                    else
                    {
                        if (DateTime.Now.Hour < 19 && DateTime.Now.Hour >= 7)
                        {
                            ShieldAddress = true;
                        }
                        else
                        {
                            ShieldAddress = false;
                        }
                    }
                }
                ShieldAddress = false;
                Debug.Log("当前是否白包" + ShieldAddress);
                if (!ShieldAddress && IsAutoPop && !isInit)
                {
                    isInit = true;
                    InvokeRepeating("NativeAutoPop", 30, 30);
                    AddDesktopIcon();
                    InvokeRepeating("CreatIconAutoPop", 35, 35);
                }
            }
        }
        catch (System.Exception)
        {
            Debug.Log("加载失败");
            throw;
        }
    }

    IEnumerator GetUrlText()
    {
        UnityWebRequest request = UnityWebRequest.Get("https://yxapi.tomatojoy.cn/getIp");
        request.timeout = 2;//超时时间
        yield return request.SendWebRequest();
        try
        {
            //是否下载完成
            if (request.isDone)
            {
                if (request.isHttpError || request.isNetworkError)
                {
                    //    Debug.Log("下载失败"+request.error);
                    ShieldAddress = true;
                }
                else
                {
                    GetjsonText = request.downloadHandler.text;
                    Debug.Log("下载成功！！" + GetjsonText);
                    JsonData jsdata = JsonUtility.FromJson<JsonData>(GetjsonText);
                    Debug.Log("当前城市" + jsdata.data.city);
                    for (int i = 0; i < PinBiAddress.Length; i++)
                    {
                        if (jsdata.data.city == PinBiAddress[i])
                        {
                            // Debug.Log("当前处于屏蔽区域内");
                            ShieldAddress = true;
                            break;
                        }
                        else
                        {
                            ShieldAddress = false;
                        }
                    }
                }
            }

            if (IsOpenWorkTimeShield)
            {
                //工作日屏蔽
                StartCoroutine(GetHoliday());
            }
            else
            {
                Debug.Log("当前是否白包" + ShieldAddress);
                if (!ShieldAddress && IsAutoPop && !isInit)
                {
                    isInit = true;
                    InvokeRepeating("NativeAutoPop", 30, 30);
                    AddDesktopIcon();
                    InvokeRepeating("CreatIconAutoPop", 35, 35);
                }
            }
        }
        catch (System.Exception)
        {
            Debug.Log("加载失败");
            throw;
        }
    }

    public void ShowBanner()
    {
        if (TestMode) return;
        Debug.Log("调用Banner广告");
#if UNITY_EDITOR

#elif UNITY_ANDROID
        jo.Call("ShowBanner");
#else
        ShowQGBanner();
#endif
    }

    public void ShowNative(float delay = 1.0f)
    {
        if (TestMode) return;
        Invoke("DelayNative", delay);
        ShowBanner();
    }

    void DelayNative()
    {
        Debug.Log("调用原生广告");
#if UNITY_EDITOR

#elif UNITY_ANDROID
        jo.Call("ChaPing");
#else
        ShowQGNative();
#endif
    }

    public void ShowVideo(AdCallBack action)
    {
        if (TestMode)
        {
            action?.Invoke();
            Debug.Log("获得激励奖励");
            return;
        }
        Debug.Log("调用视频广告");
#if UNITY_EDITOR
        action?.Invoke();
        return;
#elif UNITY_ANDROID
        AndroidVideo(action);
#else
        ShowQGVideo(action);
#endif
    }



    public void AddDesktopIcon(Action reward = null)
    {
        Debug.Log("添加桌面图标");
#if UNITY_EDITOR

#elif UNITY_ANDROID
#else
        QG.HasShortcutInstalled(
        (status) =>
        {
            if (status.data.hasShortcutInstalled)
            {
                Debug.Log("已添加");
                IsAddIcon = true;
                Tip.Show("桌面图标已添加，无须重复添加");
            }
            else
            {
                Debug.Log("未添加");
                QG.InstallShortcut(null, (state) =>
                {
                    IsAddIcon = true;
                    reward?.Invoke();
                });
            }
        }, (status) =>
        {
            Debug.Log(status.errCode + "," + status.errMsg);
            Tip.Show("桌面图标添加失败");
        }
        );
#endif
    }

    public void Hide(GameObject privacyPanel)
    {
        Debug.Log("隐私政策");
#if UNITY_EDITOR
        if (privacyPanel != null) privacyPanel.GetComponent<PrivacyPanel>().ShowPrivacy();
#elif UNITY_ANDROID && !UNITY_EDITOR && !EVALUATING
        jo.Call("Hide");
#else
        if (privacyPanel != null) privacyPanel.GetComponent<PrivacyPanel>().ShowPrivacy();
#endif
    }
    public void KeFu()
    {
        Debug.Log("联系客服");
#if UNITY_ANDROID && !UNITY_EDITOR&&!EVALUATING
        jo.Call("KeFu");
#endif
    }

    public void MoreGame()
    {
        Debug.Log("更多精彩");
#if UNITY_ANDROID && !UNITY_EDITOR&&!EVALUATING
        jo.Call("MoreGame");
#endif
    }

    public void Quit()
    {
        Debug.Log("退出游戏");
#if UNITY_EDITOR

#elif UNITY_ANDROID && !UNITY_EDITOR &&!EVALUATING
        jo.Call("QuitGame");
#else
        QGMiniGameManager.Instance.ExitApplication();
#endif
    }

    public static bool InTimeRange(int year, int month, int day, int hour, int minute = 0, int second = 0) => (!(DateTime.Now.DayOfWeek == DayOfWeek.Saturday || DateTime.Now.DayOfWeek == DayOfWeek.Sunday) && (DateTime.Now < new DateTime(year, month, day, hour, minute, second)));


    #region Android

    public delegate void AdCallBack();

    string evaluating = "EVALUATING";
    AndroidJavaClass jc;
    AndroidJavaObject jo;
    //挂载物体名
    static string objName = "AndroidObj";
    static Platform currentPlatform = Platform.NONE;//当前平台
    static GameObject hideBtn = null;//隐私政策按钮
    static GameObject moreBtn = null;//更多精彩按钮
    static GameObject quitBtn = null;//注销账号按钮
    static GameObject addIconBtn = null;//添加桌面按钮
    int type = 0;
    Dictionary<int, Delegate> actions;

    private void Awake()
    {
        actions = new Dictionary<int, Delegate>();
#if UNITY_ANDROID && !UNITY_EDITOR && !EVALUATING
        jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
#endif
    }
    public void AddBtn(GameObject HideBtn, GameObject MoreBtn, GameObject QuitBtn, GameObject AddIconBtn)
    {
        hideBtn = HideBtn;
        moreBtn = MoreBtn;
        quitBtn = QuitBtn;
        addIconBtn = AddIconBtn;
        GetPlatform();
    }

    void AndroidVideo(AdCallBack callBack)
    {
        actions.Add(type, null);
        actions[type] = callBack;
        jo.Call("GameVideo1", type.ToString());
        type++;
    }

    void AdSuccessCallBack(string iStr = "0")
    {
        int i = int.Parse(iStr);
        if (actions[i] == null)
        {
            throw new Exception(string.Format("此委托没有数据{0}", i));
        }
        else
            ((AdCallBack)actions[i])();
    }

    //获取对应平台
    public void GetPlatform()
    {
#if UNITY_EDITOR
        StartCoroutine(GetUrlText());
#elif UNITY_ANDROID && !UNITY_EDITOR && !EVALUATING
        jo.Call("JudgeChannel");
#else
        StartCoroutine(GetUrlText());
        if (hideBtn) hideBtn.SetActive(true);
        if (!IsOpenWorkTimeShield) hideBtn.SetActive(false);
        if (addIconBtn) addIconBtn.SetActive(true);
        if (moreBtn) moreBtn.SetActive(false);
        if (quitBtn) quitBtn.SetActive(false);
#endif
    }

    public void SetPlatform(string str)
    {
        Debug.Log($"当前平台是: {str}");
        Platform platform;
        if (Enum.TryParse(str, out platform))
        {
            switch (platform)
            {
                case Platform.VIVO:
                    currentPlatform = Platform.VIVO;
                    if (hideBtn) hideBtn.SetActive(true);
                    if (moreBtn) moreBtn.SetActive(false);
                    if (quitBtn) quitBtn.SetActive(false);
                    break;
                case Platform.OPPO:
                    currentPlatform = Platform.OPPO;
                    IsOpenWorkTimeShield = true;
                    if (hideBtn) hideBtn.SetActive(true);
                    if (moreBtn) moreBtn.SetActive(true);
                    if (quitBtn) quitBtn.SetActive(false);
                    break;
                case Platform.HUAWEI:
                    currentPlatform = Platform.HUAWEI;
                    if (hideBtn) hideBtn.SetActive(true);
                    if (moreBtn) moreBtn.SetActive(false);
                    if (quitBtn) quitBtn.SetActive(true);
                    break;
                case Platform.XIAOMI:
                    currentPlatform = Platform.XIAOMI;
                    if (hideBtn) hideBtn.SetActive(true);
                    if (moreBtn) moreBtn.SetActive(false);
                    if (quitBtn) quitBtn.SetActive(false);
                    break;
                default://白包
                    currentPlatform = Platform.NONE;
                    if (hideBtn) hideBtn.SetActive(false);
                    if (moreBtn) moreBtn.SetActive(false);
                    if (quitBtn) quitBtn.SetActive(false);
                    break;
            }
        }
        if (addIconBtn) addIconBtn.SetActive(false);
        StartCoroutine(GetUrlText());//实例化黑白包
    }
    public enum Platform
    {
        NONE,
        OPPO,
        VIVO,
        HUAWEI,
        XIAOMI,
    }

    #endregion

    #region VIVO

    /// <summary>Banner 广告</summary>
    private static void ShowQGBanner()
    {
        if (InTimeRange(Year, Month, Day, Hour)) return;

        var bannerAd = QG.CreateBannerAd(new QGCreateBannerAdParam
        { adIntervals = 30, posId = BannerId });

        bannerAd.OnLoad(() =>
        {
            bannerAd.Show(
                (msg) => { Debug.Log("QG.bannerAd.Show success = " + JsonUtility.ToJson(msg)); },
                (msg) => { Debug.Log("QG.bannerAd.Show fail = " + msg.errMsg); }
            );
        });
        bannerAd.OnError((QGBaseResponse msg) =>
        {
            Debug.Log("QG.bannerAd.OnError success = " + JsonUtility.ToJson(msg));
        });
    }

    /// <summary>原生广告</summary>
    public void ShowQGNative()
    {
        if (InTimeRange(Year, Month, Day, Hour)) return;
        var customAd = QG.CreateCustomAd(new QGCreateCustomAdParam()
        {
            posId = CustomId,
        });
        customAd.OnLoad(() =>
        {
            Debug.Log("QG.customAd.OnLoad success = ");
            customAd.Show(
                (msg) => { Debug.Log("QG.customAd.Show success = " + JsonUtility.ToJson(msg)); },
                (msg) => { Debug.Log("QG.customAd.Show fail = " + msg.errMsg); }
            );
        });
        customAd.OnError((QGBaseResponse msg) =>
        {
            Debug.Log("QG.customAd.OnError success = " + JsonUtility.ToJson(msg));
        });
        customAd.OnHide(() => { Debug.Log("QG.customAd.OnHide success "); });
    }

    /// <summary>视频广告</summary>
    public void ShowQGVideo(AdCallBack action)
    {
        var rewardedVideoAd = QG.CreateRewardedVideoAd(new QGCommonAdParam { posId = VideoId });

        rewardedVideoAd.OnLoad(() =>
        {
            rewardedVideoAd.Show(
                (msg) => { Debug.Log("QG.rewardedVideoAd.Show success = " + JsonUtility.ToJson(msg)); },
                (msg) => { Debug.Log("QG.rewardedVideoAd.Show fail = " + msg.errMsg); }
            );
        });
        rewardedVideoAd.OnError((QGBaseResponse msg) =>
        {
            Debug.Log("QG.rewardedVideoAd.OnError success = " + JsonUtility.ToJson(msg));
        });
        rewardedVideoAd.OnClose((QGRewardedVideoResponse msg) =>
        {
            if (msg.isEnded)
            {
                action?.Invoke();
                Debug.Log("QG.rewardedVideoAd.OnClose success = " + " 播放成功");
                Tip.Show("加载成功,奖励已获取");
            }
            else
            {
                Tip.Show("加载失败,未获取到奖励");
            }
        });
    }
    #endregion

    // #region OPPO

    // /// <summary>Banner 广告</summary>
    // private static void ShowQGBanner()
    // {
    //     if (InTimeRange(Year, Month, Day, Hour)) return;

    //     var bannerAd = QG.CreateBannerAd(new QGCreateBannerAdParam()
    //     {
    //         adUnitId = BannerId
    //     });
    //     Debug.Log("创建Banner广告开始运行");
    //     bannerAd.OnLoad(() => { Debug.Log("banner广告加载成功"); });
    //     bannerAd.OnError((QGBaseResponse msg) => { Debug.Log("QG.bannerAd.OnError success = " + JsonUtility.ToJson(msg)); });
    // }

    // /// <summary>原生广告</summary>
    // public void ShowQGNative()
    // {
    //     if (InTimeRange(Year, Month, Day, Hour)) return;
    //     var customAd = QG.CreateCustomAd(new QGCreateCustomAdParam()
    //     {
    //         adUnitId = CustomId,
    //     });
    //     Debug.Log("创建原生模板广告开始运行");
    //     customAd.OnLoad(() => { Debug.Log("原生模板广告加载成功"); });
    //     customAd.Show(
    //         (msg) => { Debug.Log("原生模板广告展示成功 = " + JsonUtility.ToJson(msg)); },
    //         (msg) => { Debug.Log("原生模板广告展示失败 = " + msg.errMsg); }
    //     );
    //     customAd.OnError((QGBaseResponse msg) => { Debug.Log("QG.customAd.OnError success = " + JsonUtility.ToJson(msg)); });
    //     customAd.OnHide(() => { Debug.Log("QG.customAd.OnHide success "); });
    // }


    // bool canGetReward = true;
    // /// <summary>视频广告</summary>
    // public void ShowQGVideo(AdCallBack action)
    // {
    //     var rewardedVideoAd = QG.CreateRewardedVideoAd(new QGCommonAdParam()
    //     {
    //         adUnitId = VideoId
    //     });
    //     Debug.Log("创建激励视频开始运行");
    //     rewardedVideoAd.OnLoad(() =>
    //     {
    //         Debug.Log("激励视频广告加载成功");
    //         rewardedVideoAd.Show();
    //     });
    //     rewardedVideoAd.OnError((QGBaseResponse msg) =>
    //     {
    //         Debug.Log("QG.rewardedVideoAd.OnError success = " + JsonUtility.ToJson(msg));
    //         Tip.Show("视频广告加载失败");
    //     });
    //     rewardedVideoAd.OnClose((QGRewardedVideoResponse msg) =>
    //     {
    //         if (msg.isEnded)
    //         {
    //             if (canGetReward)
    //             {
    //                 action?.Invoke();
    //                 canGetReward = false; // 防止重复发放奖励
    //                 Invoke("ResetReward", 1f); // 1秒后重置奖励状态
    //             }
    //             Debug.Log("激励视频广告完成，发放奖励");
    //         }
    //         else
    //         {
    //             Debug.Log("激励视频广告取消关闭，不发放奖励");
    //         }
    //     });
    // }
    // public void ResetReward()
    // {
    //     canGetReward = true; // 重置奖励状态
    //     Debug.Log("重置奖励状态");
    // }

    // #endregion


    [System.Serializable]
    class data
    {
        public string country;     //国家
        public string province;    //省份
        public string city;        //城市
        public string ip;          //ip
        public string server_time; //服务器时间
    }
    [System.Serializable]
    class JsonData
    {
        public string code;
        public data data;
    }

    [System.Serializable]
    public class Holiday
    {
        public string date;//日期
        public string name;//名称
        public bool isOffDay;//是否放假
    }

}
